<?php
/**
 *@author Connor <caokang@foxmail.com>
 *@todo
 *@link www.zeevin.com
 */
class Post extends CActiveRecord{
	const PAGE_SIZE=6;
	public $sub_content;
	public static function model($className=__CLASS__){
		return parent::model($className);
	}

	public function tableName(){
		return 'user_blogs';
	}	

	public function rules(){
		return array(
			array('subject','required','message'=>'标题不能为空'),
			array('content','required','message'=>'正文内容不能为空'),
			array('subject', 'length', 'max'=>255,'message'=>'标题太长，不能超过255个字符'),
			array('subject,content', 'safe', 'on'=>'search')
			);
	}

	public function attributeLabels(){
		return array('subject'=>'标题：','content'=>'正文：');
	}



	protected function beforeSave()
	{
		if(parent::beforeSave())
		{
			if($this->isNewRecord)
			{
				$this->ctime=$this->update_time=date('Y-m-d H:i:s');
				$this->uid=Yii::app()->user->id;
			}
			else
				$this->update_time=date('Y-m-d H:i:s');
			return true;
		}
		else
			return false;
	}




	public static function getList($uid=false){
		$condition = 'uid=:uid';
		$params['uid']=$uid?$uid:Yii::app()->user->id;
		$criteria=new CDbCriteria();
	

		$criteria->condition = $condition;
		$criteria->params = $params;
		$criteria->select = 'id,subject,SUBSTRING(content,1,100) as sub_content,ctime,update_time';
		$criteria->order = 'id DESC';
    	$count=Post::model()->count($criteria);
    	$pages=new CPagination($count);

    	// results per page
   	 	$pages->pageSize=self::PAGE_SIZE;
    	$pages->applyLimit($criteria);
    	$rs['total_num'] = $count;
    	$rs['rows'] = Post::model()->findAll($criteria);
    	$rs['pages'] = $pages;
    	return $rs;
	}

	public function del($id){
		$count = Post::model()->countBySql('select count(1) from user_blogs where uid=? and id=?',array(Yii::app()->user->id,$id));
		if($count==1){return Post::model()->deleteByPk($id);}
		else return false;
	}

}